用 PHP 與 MySQL 學習後端基礎(二)


Posted by ericcch24 on 2020-10-16

資料庫正規化

  • 兩個不同的資料庫可以透過某個欄位去建立關聯。
  • 例如第九週作業的 userscomments 資料庫的 username 欄位,可以建立兩資料庫的關聯。

資料庫 schema 參考


SQL join 語法介紹

  • 常用==left join==:左邊的資料庫取全,右邊資料庫有缺也會補上 NULL。
  • select * from A left join B on A.collum = B.collum collum 是可以把 AB 關聯起來的欄位。

join 圖形解釋參考

"SELECT ".
  "C.id as id, C.content as content, ".
  "C.created_at as created_at, U.nickname as nickname, U.username as username ".
"FROM comments as C ".
"left join users as U on C.username = U.username ". 
// 重點:select * from A left join B on A.collum = B.collum ,用 collum 把 AB 關聯起來
"ORDER BY C.id DESC"

實作分頁功能:page & cursor based

==page-based pagination==

  • 介紹 offset 與 limit
    假設有 id 1 ~ 10
    ```php=
    "SELECT * FROM comments ORDER BY id DESC LIMIT 5"
    // 只會回傳最新的 5 筆資料 >> 取 6~10

"SELECT * FROM comments ORDER BY id DESC LIMIT 5 OFFEST 3"
// 會跳過頭 3 筆資料,從第 4 筆開始算最新的 5 筆資料
// 取 7~3

`` 所以在設定分頁時limit: $item_per_page就是每頁要顯示的留言數。offest: ($page - 1) $item_per_page`表示跳過幾筆資料,可以用目前頁數來計算,例如第 2 頁就要跳過 (2-1)5 =5 筆資料,第 3 頁就要跳過 (3-1)*5 =10 筆資料。

==cursor-based pagination==

  • 依據某個指標來當作拿取資料的分界點,比較不像分頁,適合用在載入更多功能

例如:
id : 10, 9, 8, 7, 6
?before=6 取 6 之前的 id 5, 4, 3, 2, 1

id : 1, 2, 3, 4, 5
?after=5 取 5 之後的 id 6, 7, 8, 9, 10


tags: Week11

#week11







Related Posts

What Type of Laser Engraving Machine Should be Used for Stainless Steel Engraving?

What Type of Laser Engraving Machine Should be Used for Stainless Steel Engraving?

Vue.js 學習旅程Mile 8 – Class & Style Binding

Vue.js 學習旅程Mile 8 – Class & Style Binding

鏈結串列(Linked List)& 陣列(Array)

鏈結串列(Linked List)& 陣列(Array)


Comments